package com.hzo.great.leisuregreat.views;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.hzo.great.leisuregreat.R;
import com.hzo.great.leisuregreat.base.BaseActivity;
import com.hzo.great.leisuregreat.constants.UrlConstant;
import com.hzo.great.leisuregreat.dialog.LoadingDialog;
import com.hzo.great.leisuregreat.picker.JsonBean;
import com.hzo.great.leisuregreat.picker.JsonFileReader;
import com.hzo.great.leisuregreat.picker.OptionsPickerView;
import com.hzo.great.leisuregreat.utils.MyStringCallback;
import com.hzo.great.leisuregreat.utils.RequestSever;
import com.hzo.great.leisuregreat.utils.SharedPreferencesUtils;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class AddEditReceiveAddress extends BaseActivity{

    ImageView back;

    EditText receiver, phoneNum, detailAddress;

    TextView save, select, title, edit;

    String name1, phoneNum1, select1, detailAddress1;

    CheckBox isDefault;

    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //fullScreen(this, true);
        setContentView(R.layout.add_edit_receive_address);
        initView();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.back:
                finish();
                break;
            case R.id.save:
                name1 = receiver.getText().toString();
                phoneNum1 = phoneNum.getText().toString();
                select1 = select.getText().toString();
                detailAddress1 = detailAddress.getText().toString();
                if (name1.equals("")){
                    showToast("请填写收货人");
                    return;
                }

                if (phoneNum1.equals("") || !phoneNum1.startsWith("1") || phoneNum1.length() != 11){
                    ShortToast("请输入正确手机号");
                    return;
                }

                if (select1 == "请选择"){
                    showToast("请选择所在地区");
                    return;
                }

                if (detailAddress1.equals("")){
                    showToast("请填写详细地址");
                    return;
                }
                addAddress();
                break;
            case R.id.select:
                initJsonData();
                showPickerView();
                break;
            case R.id.edit:
                name1 = receiver.getText().toString();
                phoneNum1 = phoneNum.getText().toString();
                select1 = select.getText().toString();
                detailAddress1 = detailAddress.getText().toString();
                if (name1.equals("")){
                    showToast("请填写收货人");
                    return;
                }

                if (phoneNum1.equals("") || !phoneNum1.startsWith("1") || phoneNum1.length() != 11){
                    ShortToast("请输入正确手机号");
                    return;
                }

                if (select1 == "请选择"){
                    showToast("请选择所在地区");
                    return;
                }

                if (detailAddress1.equals("")){
                    showToast("请填写详细地址");
                    return;
                }
                editAddress();
                break;
        }
    }

    private void editAddress() {
        Map<String, Object> map = new HashMap<>();
        map.put("access_token", SharedPreferencesUtils.getString("access_token",""));
        map.put("Id",getIntent().getStringExtra("addressId"));
        map.put("name",name1);
        map.put("phone",phoneNum1);
        map.put("address",select1 + detailAddress1);
        map.put("isDefault",isDefault.isChecked());
        LoadingDialog.getInstance(this).showLoadDialog("");
        RequestSever.post(UrlConstant.MODIFYADDRESS_URL,map,new MyStringCallback<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                LoadingDialog.closeLoadDialog();
                JSONObject jsonObject = JSON.parseObject(result);
                switch (jsonObject.getIntValue("code")){
                    case 200:
                        //startActivity(new Intent(AddEditReceiveAddress.this,AddressManagement.class));
                        finish();
                        break;

                    default:
                        ShortToast(jsonObject.getString("message"));
                        break;
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                LoadingDialog.closeLoadDialog();
            }
        });
    }

    private void addAddress() {
        Map<String, Object> map = new HashMap<>();
        map.put("access_token", SharedPreferencesUtils.getString("access_token",""));
        map.put("customerId",SharedPreferencesUtils.getString("customerId",""));
        map.put("name",name1);
        map.put("phone",phoneNum1);
        map.put("address",select1 + detailAddress1);
        map.put("isDefault",isDefault.isChecked());
        LoadingDialog.getInstance(this).showLoadDialog("");
        RequestSever.post(UrlConstant.ADDADDRESS_URL,map,new MyStringCallback<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                LoadingDialog.closeLoadDialog();
                JSONObject jsonObject = JSON.parseObject(result);
                switch (jsonObject.getIntValue("code")){
                    case 200:
                        //startActivity(new Intent(AddEditReceiveAddress.this,AddressManagement.class));
                        finish();
                        break;

                    default:
                        ShortToast(jsonObject.getString("message"));
                        break;
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                LoadingDialog.closeLoadDialog();
            }
        });
    }

    private void ShortToast(String s) {
        Toast.makeText(AddEditReceiveAddress.this,s,Toast.LENGTH_SHORT).show();
    }

    public void initView() {

        back = (ImageView) findViewById(R.id.back);

        receiver = (EditText) findViewById(R.id.receiver);
        phoneNum = (EditText) findViewById(R.id.phoneNum);
        detailAddress = (EditText) findViewById(R.id.detailAddress);

        save = (TextView) findViewById(R.id.save);
        select = (TextView) findViewById(R.id.select);
        title = (TextView) findViewById(R.id.title);
        edit = (TextView) findViewById(R.id.edit);

        isDefault = (CheckBox) findViewById(R.id.isDefault);

        Intent intent = getIntent();
        name1 = intent.getStringExtra("name");
        phoneNum1 = intent.getStringExtra("phoneNum");
        select1 = intent.getStringExtra("address");

        if (name1 != null && phoneNum1 != null && select1 != null){
            if (select1.contains("区")){
                detailAddress1 = select1.substring(select1.indexOf("区")+1).trim();
                select1 = select1.substring(0,select1.indexOf("区")+1).trim();
            }else if(select1.contains("县")){
                detailAddress1 = select1.substring(select1.indexOf("县")+1).trim();
                select1 = select1.substring(0,select1.indexOf("县")+1).trim();
            }else {
                int shiLastIndex = select1.lastIndexOf("市");
                detailAddress1 = select1.substring(shiLastIndex+1).trim();
                select1 = select1.substring(0,shiLastIndex+1).trim();
            }
            receiver.setText(name1);
            phoneNum.setText(phoneNum1);
            select.setText(select1);
            detailAddress.setText(detailAddress1);
            title.setText("修改收货地址");
            save.setVisibility(View.GONE);
            edit.setVisibility(View.VISIBLE);
        }else {
            title.setText("新增收货地址");
            save.setVisibility(View.VISIBLE);
            edit.setVisibility(View.GONE);
        }

        back.setOnClickListener(this);
        save.setOnClickListener(this);
        select.setOnClickListener(this);
        edit.setOnClickListener(this);
    }

    public void showToast(String toast) {
        Toast.makeText(this,toast,Toast.LENGTH_SHORT).show();
    }

    private void showPickerView() {
        OptionsPickerView pvOptions=new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String text = options1Items.get(options1).getPickerViewText() + " " +
                        options2Items.get(options1).get(options2) + " " +
                        options3Items.get(options1).get(options2).get(options3);
                select.setText(text);
            }
        }).setTitleText("")
                .setDividerColor(Color.GRAY)
                .setTextColorCenter(Color.GRAY)
                .setContentTextSize(13)
                .setOutSideCancelable(false)
                .build();
        //pvOptions.setPicker(options1Items);//一级选择器
        //pvOptions.setPicker(options1Items, options2Items);//二级选择器
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {   //解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        //  获取json数据
        //province_
        String JsonData = JsonFileReader.getJson(this, "province_data.json");
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }
    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }
}
